package com.bawei.mall.user.service.impl;
import com.alibaba.fastjson2.JSON;
import com.bawei.common.core.utils.JwtUtils;
import com.bawei.common.core.utils.StringUtils;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.mall.user.domain.MallProductFootPrint;
import com.bawei.mall.user.domain.CusUser;
import com.bawei.mall.user.mapper.FootPrintMapper;
import com.bawei.mall.user.service.FootPrintService;
import com.bawei.system.domain.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class FootPrintServiceImpl implements FootPrintService {

    @Autowired
    private FootPrintMapper mallProductFootPrintMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String ACCESS_TOKEN="login_tokens:";
    @Override
    public List<MallProductFootPrint> list() {
        String token = SecurityUtils.getToken();
        String key = JwtUtils.getUserKey(token);
        String userKey = getTokenKey(key);
        String cusUserJSONString = redisTemplate.opsForValue().get(userKey);
        LoginUser loginUser= JSON.parseObject(cusUserJSONString, LoginUser.class);
        CusUser cusUser = loginUser.getCusUser();
        Integer userId = cusUser.getUserId();
        List<MallProductFootPrint> list = mallProductFootPrintMapper.list(userId);
        return list;
    }


    @Override
    public void create(MallProductFootPrint mallProductFootPrint) {
        String token = SecurityUtils.getToken();
        if(StringUtils.isEmpty(token)){
            throw new RuntimeException("token为空");
        }
        String key = JwtUtils.getUserKey(token);
        String tokenKey = getTokenKey(key);
        String s = redisTemplate.opsForValue().get(tokenKey);
        LoginUser loginUser = JSON.parseObject(s, LoginUser.class);
        CusUser cusUser = loginUser.getCusUser();
        Integer userId = cusUser.getUserId();
        String username = cusUser.getUsername();
        mallProductFootPrint.setUserId(userId);
        mallProductFootPrint.setUserName(username);
        mallProductFootPrintMapper.create(mallProductFootPrint);
    }

    @Override
    public void clear() {
        mallProductFootPrintMapper.clear();
    }

    private String getTokenKey(String key) {
        return ACCESS_TOKEN + key;
    }
}
